package com.jane.addressbook.servlet;

import java.io.IOException;
import java.sql.Connection;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jane.addressbook.bean.Addressbook;
import com.jane.addressbook.jdbc.DBConnection;
import com.jane.addressbook.manager.AddressbookManager;

public class AddOrUpdate extends HttpServlet {

	
	/**
	 * 
	 */
	private static final long serialVersionUID = 9104922934961903884L;

	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		this.doPost(req,resp);
	}
	
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		Connection conn = DBConnection.getConnection();
    	AddressbookManager manager = new AddressbookManager(conn); 
    	Addressbook ab;
    	int id;
//    	req.setCharacterEncoding("utf-8");
    	String name = req.getParameter("name");
    	String tel1 = req.getParameter("tel1");
    	String tel2 = req.getParameter("tel2");
    	String sex = req.getParameter("sex");
    	String birthday = req.getParameter("birthday");
    	String email = req.getParameter("email");
    	String adress = req.getParameter("adress");
    	if(req.getParameter("id")!=""){
    		id = Integer.parseInt(req.getParameter("id"));
    		ab = new Addressbook(id,name,tel1,tel2,sex,birthday,email,adress);
    		manager.update(ab);
    	}else{
    		id = manager.getMaxId() + 1;
    		ab = new Addressbook(id,name,tel1,tel2,sex,birthday,email,adress);
    		manager.add(ab);
    	}
    	resp.sendRedirect("list");  
        DBConnection.closeConnection(conn);
	}
}
